﻿namespace IPScanner
{
    public partial class FormRange : Form
    {
        private List<IPRangeItem> _items = new List<IPRangeItem>();

        public List<IPRangeItem> RangeItems { get => _items; }

        public FormRange()
        {
            InitializeComponent();
        }

        public FormRange(List<IPRangeItem> rangeItems) : this()
        {
            _items = rangeItems;
            lsvRange.VirtualListSize = _items.Count;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (_items.Any(x => x.ToString() == $"{numIP1.Value}.{numIP2.Value}.{numIP3.Value}.{numIP4.Value} - {numIP5.Value}"))
                return;

            _items.Add(new IPRangeItem
            {
                Status = RangeItemStatus.None,
                Enable = true,
                IpPrefix = $"{numIP1.Value}.{numIP2.Value}.{numIP3.Value}.",
                StartAddress = (int)numIP4.Value,
                EndAddress = (int)numIP5.Value
            });

            lsvRange.VirtualListSize = _items.Count;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lsvRange.SelectedIndices.Count == 0) return;

            foreach (int index in lsvRange.SelectedIndices)
            {
                _items.RemoveAt(index);
                lsvRange.VirtualListSize--;
            }
        }

        private void btnEnable_Click(object sender, EventArgs e)
        {
            if (lsvRange.SelectedIndices.Count == 0) return;

            foreach (int index in lsvRange.SelectedIndices)
            {
                _items[index].Enable = true;
            }
        }

        private void btnUnable_Click(object sender, EventArgs e)
        {
            if (lsvRange.SelectedIndices.Count == 0) return;

            foreach (int index in lsvRange.SelectedIndices)
            {
                _items[index].Enable = false;
            }
        }

        private void lsvRange_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            if (_items.Count == 0) return;

            if (e.ItemIndex >= _items.Count) return;

            var item = _items[e.ItemIndex];
            var subItem = new ListViewItem(new[] { item.ToString(), item.Enable ? "启用" : "停用" });
            e.Item = subItem;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}
